package com.server;


import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class JServer extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);


		java.lang.System.setProperty("java.net.preferIPv4Stack", "true");
		java.lang.System.setProperty("java.net.preferIPv6Addresses", "false");



		Server server = new Server(8080);
		Log.v("verbose", "server cr8ed");

		server.setHandler(new HelloJetty());
		Log.v("verbose", "handeler set");
		Log.v("verbose", getLocalIpAddress());


		try {
			server.start();
			Log.v("verbose", "server started");
			server.join();
			Log.v("verbose", "server joined");


		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
		}
		return null;
	}


	static public class HelloJetty extends AbstractHandler
	{
		public void handle(String target,
				Request baseRequest,
				HttpServletRequest request,
				HttpServletResponse response) 
		throws IOException, ServletException
		{

			Log.v("<>>><><><><>", "handler!");
			response.setContentType("text/html;charset=utf-8");
			response.setStatus(HttpServletResponse.SC_OK);
			baseRequest.setHandled(true);
			response.getWriter().println("<h1>Hello World</h1>");

			//        	
			//        	System.err.println(baseRequest.getHeader("client"));
			//        	
			////        	DataInputStream in = new DataInputStream(baseRequest.getInputStream());
			////        	String s = (String) in.readUTF();
			////    		System.err.println(s);
			//    		
			//    		
			//            response.setStatus(HttpServletResponse.SC_OK);
			//            baseRequest.setHandled(true);
			//            response.addHeader("server", "response");
			//
			//        	OutputStream out = response.getOutputStream();
			//        	DataOutputStream oop = new DataOutputStream(out);
			//            
			//        	oop.writeUTF("from server");
			//        }
		}
	}

	public static class SendFile extends AbstractHandler
	{


		public void handle(String target,
				Request baseRequest,
				HttpServletRequest request,
				HttpServletResponse response) 
		throws IOException, ServletException 
		{
			System.err.println("SendfileHandler");
			baseRequest.setHandled(true);
			response.setStatus(HttpServletResponse.SC_OK);

			//mimetyes for streams
			response.setContentType("application/octet-stream");

			// sendfile
			File myFile = new File ("source.txt");
			if(!myFile.exists()){
				myFile.createNewFile();
			}


			byte [] mybytearray  = new byte [(int)myFile.length()];
			FileInputStream fis = new FileInputStream(myFile);
			BufferedInputStream bis = new BufferedInputStream(fis);
			bis.read(mybytearray,0,mybytearray.length);
			OutputStream os = response.getOutputStream();
			System.out.println("Sending");
			System.err.println("Sending...");

			//write one byte at a time to calculate speed
			os.write(mybytearray,0,mybytearray.length);
			os.flush();
			System.err.println("Done");
		}
	}
} 
